package qq

import (
	"api-go/cache"
	"api-go/serializer"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/PuerkitoBio/goquery"
	"github.com/go-redis/redis/v8"
)

type Banner struct {
}

var ctx = context.Background()

// //获取首页轮播图(服务器部署失效)
// func (service *Banner) Banner() *serializer.Response {

// 	url := "https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg"

// 	res, err := util.QQGet(url)
// 	if err != nil {
// 		return err
// 	}
// 	return serializer.OkResponse(res)
// }

//获取首页轮播图(通过爬虫)
func (service *Banner) Banner() *serializer.Response {
	//定义redis key和判断redis是否有该值
	redisKey := "qq-banner"
	redisResult, err := cache.RedisClient.Get(ctx, redisKey).Result()
	//若redis没有该值则执行获取
	if err == redis.Nil {
		out := []map[string]interface{}{}
		url := "https://c.y.qq.com/node/musicmac/v6/index.html"
		res, err := http.Get(url)
		if err != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		defer res.Body.Close()
		if res.StatusCode != 200 {
			fmt.Printf("status code error: %s\n", res.Status)
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		g, e := goquery.NewDocumentFromReader(res.Body)

		if e != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		c := g.Find(".focus__pic.js_focus_pic")
		c.Each(func(i int, content *goquery.Selection) {
			//获取id(专辑)
			a, _ := content.Find("a").Attr("data-rid")
			//获取类别（10002专辑）
			b, _ := content.Find("a").Attr("data-type")
			//获取图片
			c, _ := content.Find("img").Attr("srcset")

			arr := map[string]interface{}{
				"id":   a,
				"type": b,
				"img":  c,
			}
			out = append(out, arr)

		})

		//将结果转为Json数据
		b, e := json.Marshal(out)
		if e != nil {
			fmt.Println(err)
		}
		//转为string存入redis
		e = cache.RedisClient.Set(ctx, redisKey, string(b), 24*time.Hour).Err()
		if e != nil {
			fmt.Println("err1", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}

		return serializer.OkResponse(out)
	} else if err != nil {
		fmt.Println("err2", err)
		return serializer.ErrorResponse(serializer.RedisError)
	} else {
		//将从redis获取的结果（string类型）转为map[string]inerface{}
		bodyMapData := []map[string]interface{}{}
		err = json.Unmarshal([]byte(redisResult), &bodyMapData)
		if err != nil {
			fmt.Println("err3", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}
		return serializer.OkResponse(bodyMapData)
	}

}
